﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sausage.Common;
using Sausage.Web.Code;
using Sausage.Web.DataModel;
using Sausage.Web.Domain;
using Sausage.Web.Models;

namespace Sausage.Web.Controllers
{
    /// <summary>
    /// 养护日志控制器
    /// </summary>
    /// <remarks></remarks>
    /// <history>
    /// [zanezeng]               2012/02/22 12:26    创建
    /// </history>
    public class MaintainJournalController : Controller
    {
        /// <summary>
        /// 默认动作。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [RequireAuthorization]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 默认动作。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [RequireAuthorization]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Submit()
        {
            return View();
        }

        /// <summary>
        /// 审核。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [RequireAuthorization]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Audit()
        {
            return View();
        }

        /// <summary>
        /// 确认。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [RequireAuthorization]
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult Confirm()
        {
            return View();
        }

        /// <summary>
        /// 查看养护日志。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult ViewJournal(Guid journalID)
        {
            //返回视图
            return View(MaintainJournalHelper.GetMaintainJournalByID(journalID));
        }

        /// <summary>
        /// 查看养护日志。
        /// </summary>
        /// <returns></returns>
        /// <remarks></remarks>
        [HandleError(Order = 3, ExceptionType = typeof(UnauthenticatedException), View = "Unauthenticated")]
        [HandleError(Order = 2, ExceptionType = typeof(UnauthorizedException), View = "Unauthorized")]
        [HandleError(Order = 1, ExceptionType = typeof(Exception), View = "Exception")]
        public ActionResult ViewQuantityJournal(Guid quantityID)
        {
            //返回视图
            return View(MaintainQuantityHelper.GetMaintainQuantityByID(quantityID));
        }

        /// 查询
        /// </summary>
        /// <param name="query">查询条件模型。</param>
        /// <returns>查询的工程项目信息列表</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Select(JosnPagingQueryModel query)
        {
            var result = MaintainJournalHelper.Select(query);

            //返回结果
            return new JsonNetResult()
            {
                Data = new JsonResultViewModel
                {
                    success = true,
                    data = result.Data,
                    total = result.Total,
                    message = "养护日志加载成功！"
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        /// 查询
        /// </summary>
        /// <param name="query">查询条件模型。</param>
        /// <returns>查询的工程项目信息列表</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult AuditSelect(JosnPagingQueryModel query)
        {
            var result = MaintainJournalHelper.AuditSelect(query);

            //返回结果
            return new JsonNetResult()
            {
                Data = new JsonResultViewModel
                {
                    success = true,
                    data = result.Data,
                    total = result.Total,
                    message = "养护日志加载成功！"
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }


        /// 查询
        /// </summary>
        /// <param name="query">查询条件模型。</param>
        /// <returns>查询的工程项目信息列表</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult SubmitSelect(JosnPagingQueryModel query)
        {
            var result = MaintainJournalHelper.SubmitSelect(query);

            //返回结果
            return new JsonNetResult()
            {
                Data = new JsonResultViewModel
                {
                    success = true,
                    data = result.Data,
                    total = result.Total,
                    message = "养护日志加载成功！"
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        /// 查询
        /// </summary>
        /// <param name="query">查询条件模型。</param>
        /// <returns>查询的工程项目信息列表</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult ConfirmSelect(JosnPagingQueryModel query)
        {
            var result = MaintainJournalHelper.ConfirmSelect(query);

            //返回结果
            return new JsonNetResult()
            {
                Data = new JsonResultViewModel
                {
                    success = true,
                    data = result.Data,
                    total = result.Total,
                    message = "养护日志加载成功！"
                },
                JsonRequestBehavior = JsonRequestBehavior.AllowGet
            };
        }

        /// <summary>
        /// 详细
        /// </summary>
        /// <returns>执行结果</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Details(Guid id)
        {
            var maintainJournal = MaintainJournalHelper.GetMaintainJournalByID(id);
            if (maintainJournal == null)
                return Json(new JsonResultViewModel { success = true, message = "找不到此养护日志！" },
                            JsonRequestBehavior.AllowGet);

            var data = new
                           {
                               JournalID = maintainJournal.JournalID,
                               OrganizationID = maintainJournal.OrganizationID,
                               Organization = maintainJournal.Organization.OrganizationName,
                               Weather = maintainJournal.Weather,
                               Content = maintainJournal.Content,
                               CreateDate = maintainJournal.CreateDate,
                               Applicant = maintainJournal.Applicant,
                               ApplicationDate = maintainJournal.ApplicationDate,
                               Auditor = maintainJournal.Auditor,
                               AuditedDate = maintainJournal.AuditedDate,
                               Approver = maintainJournal.Approver,
                               ApprovedDate = maintainJournal.ApprovedDate,
                               State = maintainJournal.State,
                               IsDelay = maintainJournal.IsDelay,
                               Memo = maintainJournal.Memo
                           };

            return new JsonNetResult()
                       {
                           Data = new JsonResultViewModel
                                      {
                                          success = true,
                                          total = 1,
                                          data = data,
                                          message = "加载养护日志成功！"
                                      },
                           JsonRequestBehavior = JsonRequestBehavior.AllowGet
                       };
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns>执行结果</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Delete(MaintainJournalListRow data)
        {
            MaintainJournalHelper.DeleteMaintainJournal(data.JournalID);
            return Json(new JsonResultViewModel { success = true, message = "养护日志删除成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <returns>执行结果</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        [ValidateInput(false)]
        public JsonResult Update(MaintainJournalListRow data)
        {
            MaintainJournalHelper.UpdateMaintainJournal(data);
            return Json(new JsonResultViewModel { success = true, message = "养护日志更新成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <returns>执行结果</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult UpdateState(Guid id, int state)
        {
            MaintainJournalHelper.UpdateMaintainJournalState(id, state);
            return Json(new JsonResultViewModel { success = true, message = "养护日志状态更新成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 创建
        /// </summary>
        /// <returns>创建结果。</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        [ValidateInput(false)]
        public JsonResult Create(MaintainJournalListRow data)
        {
            string errorMessage;
            if (!Helper.CouldSet(data.ApplicationDate, out errorMessage))
                return Json(new JsonResultViewModel { success = false, message = errorMessage, data = Guid.Empty }, JsonRequestBehavior.AllowGet);

            var journalID = MaintainJournalHelper.CreateMaintainJournal(data);
            return Json(new JsonResultViewModel { success = true, message = "养护日志创建成功！", data = journalID }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 查询图片信息
        /// </summary>
        /// <returns>查询结果。</returns>
        /// <remarks></remarks>
        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult Photos(Guid journalID)
        {
            var data = MaintainJournalHelper.GetJournalPhotos(journalID);
            return Json(new JsonResultViewModel { success = true, message = "养护日志提交成功!", data = data }, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public ActionResult Photo(Guid photoID)
        {
            var photo = MaintainJournalHelper.GetPhoto(photoID);

            if (photo == null)
                return Json(new JsonResultViewModel { success = false, message = "没有此养护日志照片！", data = Guid.NewGuid() }, JsonRequestBehavior.AllowGet);

            return
                new ImageResult(
                    string.Concat(Server.MapPath(Utility.MaintainJournalFolder), Path.DirectorySeparatorChar,
                                  photo.PhotoID, photo.FileExtension),
                    Utility.GetContentTypeFromFileExtension(photo.FileExtension));
        }

        /// <summary>
        /// 删除照片
        /// </summary>
        /// <returns>删除结果。</returns>
        /// <remarks></remarks>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult DeletePhoto(Guid photoID)
        {
            if (MaintainJournalHelper.DeleteMaintainJournalPhoto(photoID))
                return Json(new JsonResultViewModel { success = true, message = "养护日志图片删除成功！", data = Guid.NewGuid() },
                            JsonRequestBehavior.AllowGet);

            return Json(new JsonResultViewModel { success = false, message = "养护日志图片删除失败！", data = Guid.NewGuid() },
                        JsonRequestBehavior.AllowGet);
        }


        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="quantityID">The quantity ID.</param>
        /// <returns>
        /// 执行结果
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult ExecuteSubmit(Guid[] journals)
        {

            MaintainJournalHelper.ExecuteSubmit(journals);
            //返回结果
            return Json(new JsonResultViewModel { success = true, message = "养护日志提交成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 审核
        /// </summary>
        /// <param name="labours">The labours.</param>
        /// <param name="name">The auditor.</param>
        /// <returns>
        /// 执行结果
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult ExecuteAudit(Guid[] journals, bool passed, string comment)
        {
            MaintainJournalHelper.ExecuteAudit(journals, passed, comment);
            //返回结果
            return Json(new JsonResultViewModel { success = true, message = "养护日志审核成功！" }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 批准
        /// </summary>
        /// <param name="labours">The labours.</param>
        /// <param name="auditor">The auditor.</param>
        /// <returns>
        /// 执行结果
        /// </returns>
        [HttpPost]
        [JsonHandleError]
        [PermissionCheckAttribute("*")]
        public JsonResult ExecuteConfirm(Guid[] journals, bool passed, string comment)
        {
            MaintainJournalHelper.ExecuteConfirm(journals, passed, comment);
            //返回结果
            return Json(new JsonResultViewModel { success = true, message = "养护日志审核成功！" }, JsonRequestBehavior.AllowGet);
        }
    }
}
